package com.ruoyi.inspection.service.impl;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.inspection.controller.GovernInspectionTaskPush;
import com.ruoyi.inspection.domain.*;
import com.ruoyi.inspection.mapper.*;
import com.ruoyi.inspection.service.GovernCheckTaskInfoService;
import com.ruoyi.inspection.service.GovernCheckTaskPlanService;
import com.ruoyi.inspection.utils.BeanUtils;
import com.ruoyi.inspection.utils.IdFactory;
import com.ruoyi.system.domain.SysDanger;
import com.ruoyi.system.mapper.SysDangerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 政府专项检查表(GovernCheckTaskInfo)表服务实现类
 *
 * @author makejava
 * @since 2024-06-19 16:15:55
 */
@Service("governCheckTaskInfoService")
public class GovernCheckTaskInfoServiceImpl implements GovernCheckTaskInfoService {
    @Autowired
    private GovernCheckTaskPlanService governCheckTaskPlanService;
    @Resource
    private GovernCheckTaskInfoMapper governCheckTaskInfoMapper;
    @Resource
    private GovernInspectionTaskPush governInspectionTaskPush;
    @Resource
    private GovernCheckTaskPlanItemMapper governCheckTaskPlanItemMapper;

    @Resource
    private GovernCheckTaskItemMapper governCheckTaskItemMapper;
    @Resource
    private GovernCheckTaskMapper governCheckTaskMapper;
    @Resource
    private SysDangerMapper sysDangerMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param governTaskInfoId 主键
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskInfo queryById(Long governTaskInfoId) {
        return this.governCheckTaskInfoMapper.queryById(governTaskInfoId);
    }

    /**
     * 查询
     *
     * @param governCheckTaskId 筛选条件
     * @param checkType 筛选条件
     * @return 查询结果
     */
    @Override
    public GovernCheckTaskInfo selectGovernCheckTaskInfo(String governCheckTaskId, String checkType) {
        GovernCheckTaskInfo governCheckTaskInfo = new GovernCheckTaskInfo();
        governCheckTaskInfo.setGovernCheckTaskId(governCheckTaskId);
        governCheckTaskInfo.setGovernCheckTaskTypeName(checkType);

        List<GovernCheckTaskInfo> list = this.governCheckTaskInfoMapper.queryAllByLimit(governCheckTaskInfo);
        return StringUtils.isEmpty(list) ? null : list.get(0);
    }

    /**
     * 分页查询
     *
     * @param governCheckTaskInfo 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskInfo> queryByPage(GovernCheckTaskInfo governCheckTaskInfo) {
        return this.governCheckTaskInfoMapper.queryAllByLimit(governCheckTaskInfo);
    }

    /**
     * 新增数据
     *
     * @param governCheckTaskInfo 实例对象
     * @return 实例对象
     */
    @Override
    public void insert(GovernCheckTaskInfo governCheckTaskInfo) {
        governCheckTaskInfo.setGovernTaskInfoId(IdFactory.newLongId());
        governCheckTaskInfo.setGovernCreateDate(new Date());
        this.governCheckTaskInfoMapper.insert(governCheckTaskInfo);
    }

    /**
     * 修改数据
     *
     * @param governCheckTaskInfo 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public GovernCheckTaskInfo update(GovernCheckTaskInfo governCheckTaskInfo, String userName) {
        governCheckTaskInfo.setGovernUpdateDate(new Date());
        governCheckTaskInfo.setGovernUpdateBy(userName);
        this.governCheckTaskInfoMapper.update(governCheckTaskInfo);

        pushTaskPlan(governCheckTaskInfo.getGovernTaskInfoId(), userName);
        updateTaskCompleteTime(governCheckTaskInfo.getGovernTaskInfoId());

        return this.queryById(governCheckTaskInfo.getGovernTaskInfoId());
    }

    /**
     * 向市局推送已完成的检查计划
     *
     * @param governTaskInfoId
     * @param userName
     * @return
     */
    public boolean pushTaskPlan(Long governTaskInfoId, String userName) {
        GovernCheckTaskPlan governCheckTaskPlan = new GovernCheckTaskPlan();
        governCheckTaskPlan.setGovernDeleted(0);
        governCheckTaskPlan.setGovernPushStatus(0);
        governCheckTaskPlan.setGovernCheckVerify(1);
        governCheckTaskPlan.setGovernTaskInfoId(governTaskInfoId);
        List<GovernCheckTaskPlan> list = governCheckTaskPlanService.queryByPage(governCheckTaskPlan);
        if (StringUtils.isEmpty(list)) {
            return false;
        }

        for (GovernCheckTaskPlan plan : list) {
            // 确认完成专项检查-市局推送
            if (!governInspectionTaskPush.pushSpecialCheckRecord(plan)) {
                return false;
            }

            GovernCheckTaskPlan entity = new GovernCheckTaskPlan();
            entity.setGovernTaskPlanId(plan.getGovernTaskPlanId());
            entity.setGovernUpdateDate(new Date());
            entity.setGovernUpdateBy(userName);
            entity.setGovernPushStatus(1);
            governCheckTaskPlanService.update(entity);
        }

        return true;
    }

    /**
     * 更新专项检查的完成时间
     *
     * @param governTaskInfoId
     * @return
     */
    public boolean updateTaskCompleteTime(Long governTaskInfoId) {
        // 查询所有的检查计划
        GovernCheckTaskPlan governCheckTaskPlan = new GovernCheckTaskPlan();
        governCheckTaskPlan.setGovernDeleted(0);
        governCheckTaskPlan.setGovernTaskInfoId(governTaskInfoId);
        List<GovernCheckTaskPlan> list = governCheckTaskPlanService.queryByPage(governCheckTaskPlan);

        // 已确认且已推送市局的检查计划
        governCheckTaskPlan.setGovernPushStatus(1);
        List<GovernCheckTaskPlan> pushList = governCheckTaskPlanService.queryByPage(governCheckTaskPlan);

        if (StringUtils.isEmpty(list) || (!StringUtils.isEmpty(pushList) && (pushList.size() == list.size())) ) {
            GovernCheckTaskInfo TaskInfo = new GovernCheckTaskInfo();
            TaskInfo.setGovernTaskCompleteTime(new Date());
            TaskInfo.setGovernTaskInfoId(governTaskInfoId);
            this.governCheckTaskInfoMapper.update(TaskInfo);
        }

        return true;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.governCheckTaskInfoMapper.deleteById(id) > 0;
    }

    /**
     * 批量删除数据
     *
     * @param ids 主键
     * @return 是否成功
     */
    @Override
    public int deleteByIds(Long[] ids) {
        return this.governCheckTaskInfoMapper.deleteByIds(ids);
    }

    @Override
    @Transactional
    public void taskSalvage(Long governTaskInfoId, String userName) {
        GovernCheckTaskInfo governCheckTaskInfo = governCheckTaskInfoMapper.queryById(governTaskInfoId);

        // 新增检查计划（绑定危险源与检查任务）
        List<Long> taskPlanIds = addTaskPlan(governCheckTaskInfo, userName, 0);

        // 添加任务计划检查项
        addTaskPlanItem(taskPlanIds, governCheckTaskInfo.getGovernCheckTaskId(), userName);
    }

    /**
     * 新增检查计划（绑定危险源与检查任务）
     *
     * @param governCheckTaskInfo
     * @param userName
     */
    @Transactional
    public List<Long> addTaskPlan(GovernCheckTaskInfo governCheckTaskInfo, String userName, int type) {
        List<SysDanger> dangers = sysDangerMapper.listByLevels(InspectionConstant.WEI_XIAN_YUAN_JI_BIE);
        if (StringUtils.isEmpty(dangers)) {
            return null;
        }

        List<Long> taskPlanIds = new ArrayList<>();
        for (SysDanger danger : dangers) {
            // 判断该危险源已经关联任务
            GovernCheckTaskPlan governCheckTaskPlan = new GovernCheckTaskPlan();
            governCheckTaskPlan.setGovernInvolveDanger(danger.getDangerName());
            governCheckTaskPlan.setGovernTaskInfoId(governCheckTaskInfo.getGovernTaskInfoId());
            if (governCheckTaskPlanService.selectGovernCheckTaskPlan(governCheckTaskPlan) != null) {
                continue;
            }

            /** 添加任务计划 **/
            BeanUtils.copyBeanProp(governCheckTaskPlan, governCheckTaskInfo);
            governCheckTaskPlan.setGovernInvolveDangerCode(danger.getDangerCode());
            governCheckTaskPlan.setGovernInvolveDanger(danger.getDangerName());
            governCheckTaskPlan.setGovernTaskRegisterTime(new Date());
            governCheckTaskPlan.setGovernCreateBy(userName);
            governCheckTaskPlan.setType(type);
            governCheckTaskPlanService.insert(governCheckTaskPlan);

            taskPlanIds.add(governCheckTaskPlan.getGovernTaskPlanId());
        }

        return taskPlanIds;
    }

    /**
     * 在检查计划下 添加检查项
     * @param taskPlanIds
     * @param taskId
     * @param userName
     */
    @Transactional
    public void addTaskPlanItem(List<Long> taskPlanIds, String taskId, String userName) {
        List<GovernCheckTaskItem> governCheckTaskItems = governCheckTaskItemMapper.queryByTaskId(taskId);
        if (StringUtils.isEmpty(governCheckTaskItems)) {
            return ;
        }

        for (Long taskPlanId : taskPlanIds) {
            List<GovernCheckTaskPlanItem> collect = governCheckTaskItems.stream()
                    .map(JSONObject::new)
                    .map(i -> i.toBean(GovernCheckTaskPlanItem.class))
                    .map(i -> i.setPlanId(i, taskPlanId, userName))
                    .collect(Collectors.toList());
            governCheckTaskPlanItemMapper.insertBatch(collect);
        }
    }

    /**
     * 新增市、省、部级专项检查任务
     *
     * @param taskId
     * @param checkType
     * @return
     */
    @Override
    @Transactional
    public int saveTaskInfo(String taskId, String checkType, String loginUser) {
        if (StringUtils.isEmpty(taskId)) {
            throw new ServiceException("检查任务不能为空");
        }
        if (StringUtils.isEmpty(checkType)) {
            throw new ServiceException("检查类型不能为空");
        }
        if ("企业自查".equals(checkType)) {
            throw new ServiceException("检查类型不能为企业自查");
        }
        GovernCheckTaskInfo taskInfo = this.selectGovernCheckTaskInfo(taskId, checkType);
        if (taskInfo!=null) {
            throw new ServiceException("专项检查任务已经存在");
        }

        GovernCheckTask task = governCheckTaskMapper.queryByTaskId(taskId);
        if (task==null) {
            throw new ServiceException("政府下发任务不存在");
        }

        taskInfo = new GovernCheckTaskInfo();
        BeanUtils.copyBeanProp(taskInfo, task);
        taskInfo.setGovernCheckTaskTypeName(checkType);
        taskInfo.setGovernCreateBy(loginUser);
        taskInfo.setGovernInvolve(1);

        // 新增检查任务
        this.insert(taskInfo);
        // 新增检查计划（也就是绑定危险源和检查任务）
        this.addTaskPlan(taskInfo, loginUser, 1);

        return 1;
    }

}
